package com.example.demo.ws;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;

/**
 * sse模式长轮询
 * file:///Users/yuanby/yby/gitee/前端/sseDemo.html
 */
@RequestMapping("/sse")
@RestController
public class SseController {
    private static final Logger log = LoggerFactory.getLogger(SseController.class);

    private final ConcurrentHashMap<String, SseEmitter> sseCache = new ConcurrentHashMap<>();

    @GetMapping("/sse")
    public SseEmitter handleSse(@RequestParam(name = "msg") String msg) throws ExecutionException, InterruptedException, IOException {
        log.info("sse msg: {}", msg);

        // 创建一个新的SseEmitter实例，超时时间为30秒
        SseEmitter emitter = new SseEmitter(30_000L);

        // 方式一：返回一次结果 创建一个ScheduledExecutorService来定时发送事件
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Future<String> future = executorService.submit(() -> {
            // TODO 模拟业务执行业务时间
            TimeUnit.SECONDS.sleep(3);
            // 发送事件，事件名称为"message"，数据为当前时间戳
            return msg + "hashlib处理结果是: " + WebPollController.sha256(msg);
        });
        //
        emitter.send(SseEmitter.event().name("message").data(future.get()));
        emitter.complete(); // 业务处理结束  关闭连接资源


        // 方式二：返回多行结果  每秒发送一个当前时间的消息
//        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
//        executor.scheduleAtFixedRate(() -> {
//            try {
//                // TODO  处理业务
//                // 发送事件，事件名称为"message"，数据为当前时间戳
//                String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//                emitter.send(SseEmitter.event().name("message").data(msg + "您好，现在是北京时间: " + date));
//
//            } catch (IOException e) {
//                // 发送失败时完成该Emitter
//                emitter.completeWithError(e);
//            }
//        }, 0, 1, TimeUnit.SECONDS);
//
//         //在30秒后完成该Emitter
//        executor.schedule(() -> emitter.complete(), 30, TimeUnit.SECONDS);

        return emitter;
    }
}
